package club.ljwang.controller;

import club.ljwang.constant.MessageConstant;
import club.ljwang.entity.Result;
import club.ljwang.pojo.Menu;
import club.ljwang.pojo.Menu2;
import club.ljwang.service.MenuService;
import club.ljwang.service.RoleService;
import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.dubbo.config.annotation.Reference;


import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/menu")
public class MenuController {

    @Reference
    MenuService menuService;
    @Reference
    RoleService roleService;

    @RequestMapping("/getMenus")
    public Result getMenus(@RequestParam(name = "id",required = false,defaultValue = "0") Integer id, Integer roleId){
        //所有菜单
        List<Menu2> menus =  menuService.getMenus(id);
        //角色已经分配的菜单
        List<Integer> menuIds = roleService.getMenus(roleId);
        Map map = new HashMap();
        map.put("menus",menus);
        map.put("menuIds",menuIds);

        //排除父菜单id，
        List<Integer> parentIds = new ArrayList<>();
        getParentId(menus,parentIds);
        menuIds.removeAll(parentIds);

        return new Result(true, MessageConstant.GET_MENU_SUCCESS,map);
    }

    private void getParentId(List<Menu2> menus,List<Integer> parentIds){
        if(CollectionUtil.isNotEmpty(menus)){
            for (Menu2 menu : menus) {
                List<Menu2> children = menu.getChildren();
                if(CollectionUtil.isNotEmpty(children)){
                    parentIds.add(menu.getId());
                }
                //递归找儿子菜单是否还有儿子
                getParentId(children,parentIds);
            }
        }
    }

    @RequestMapping("/add")
    public Result add(@RequestBody Menu menu){
        try {
            menuService.add(menu);
            return new Result(true,"菜单添加成功");
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,"菜单添加失败");
        }
    }

}
